var util = require('../../utils/util.js')
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var reload = true;
var page = 1;
var hasMore = true;
var loadingMore = false;

var SDKVersion = '';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    util: util,
    imgDomain: app.globalData.imgDomain,

    classlysData: '',

    ghsData: [],
    hasData: true,

    uid: 0,
    token: '',
    openid: '',
    canEdit: 0,

    bottom_nav_data: [],
    isIphone_x: false,
    nav_bgColor: '#ffffff',

    shouqian_phone: '',
    colorSet: '',
    wz_item_img_w_1: 300,

    isShow: false,

    orgInfo: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    var tc = app.get_tc();
    var that = this;
    that.setData({
      tc: tc,
    });
    wx.showLoading({
      title: tc == 1 ? '加載中' : '加载中',
      mask: 'true'
    });
    if (util.orgid == 14148){
      var titlename = tc == 1 ? '簽到' : '签到';    
    } else if (util.orgid == 15671) {
      var titlename = tc == 1 ? '知名企業' : '知名企业';
    } else if (util.orgid == 18535) {
      var titlename = tc == 1 ? '家家市場' : '家家市场';
    } else{
      var titlename = tc == 1 ? '名牌鋪' : '名牌铺';    
    } //家家市场
    wx.setNavigationBarTitle({
      title: titlename,
    }); 

    page = 1;
    hasMore = true;
    loadingMore = false;

    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "wxcheck"
      },
      success: function (responseData) {
        console.log("wxcheck show = " + responseData.data.isShow);
        that.setData({
          isShow: responseData.data.isShow
        });
      }
    });

    //获取小程序信息
    app.GetUserInfo(util.orgid, function (res) {
      console.log("小程序信息：", res);
      that.setData({
        orgInfo: res
      })
    });
    
    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color,
      })
      that.resetNavColor();
    });

    //初始化底部导航
    var b_nav_data = app.getBottomNavData('ghs_list/ghs_list', function (data) {
      that.setData({
        bottom_nav_data: data,
        nav_bgColor: data[0].bgcolor,
      });
    });

    wx.getSystemInfo({
      success: function (res) {
        SDKVersion = res.SDKVersion;
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          tc: app.get_tc(),
          isIphone_x: isIphone_x,
          screen_h:res.windowHeight,
          wz_item_img_w_1: res.windowWidth - 25
        });
      }
    })

    reload = true;
    //当前登录用户信息
    app.LoginUserInfo(function (res) {
      var authFail = res == -1;//用户拒绝授权
      if (!authFail) {
        //更新数据
        that.setData({
          uid: res.uid,
          token: res.token,
          openid: res.wxsmall_openid
        });
      }

    });
    //获取关于等信息
    app.getAllAbout('shouqian', function (res) {
      that.setData({
        shouqian_phone: res
      })
    });
    //读取文字分类
    this.loadGHS(1);
  },

  

  loadMore: function (e) {
    if (hasMore && !loadingMore) {
      loadingMore = true;
      page++;
      this.loadGHS(page);
    } else {
      console.log("没有更多了");
    }
  },

  // 读取动态 （近况）
  loadGHS: function (cpage) {
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "getghs",
      orgid: util.orgid,
      page: cpage,
      num: 10
    }
    util.api({
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("供货商数据：", result);
        if (!result.msg) {
          // result.forEach(function (m, i) {
          //   if (m.photos) {
          //     result[i].photosData = m.photos.split(",");
          //   }
          //   result[i].message = app.parseHTMLText(m.message);
          // });

          if (cpage <= 1) {
            that.setData({
              ghsData: result
            });

          } else {

            that.setData({
              ghsData: that.data.ghsData.concat(result)
            });

          }
        } else {
          if (cpage <= 1) {

            that.setData({
              ghsData: []
            });

          }

          hasMore = false;


        }
        if (util.orgid == 18535) {
          var ghsData = that.data.ghsData
          for (var i = 0; i < ghsData.length; i++) {
            if (ghsData[i].gcataid!=0 ) {
              ghsData.splice(i, 1);
              i--
            }
          }
          that.setData({
            ghsData: ghsData
          });

        }
        loadingMore = false;

        if (that.data.ghsData.length <= 0) {
          that.setData({
            hasData: false
          })
        } else {
          that.setData({
            hasData: true
          })
        }
        wx.hideLoading();
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  //页面分享
  onShareAppMessage: function () {
    var that = this;
    var inviteuid = that.data.loginuid ? that.data.loginuid : '';
    console.log("分享id" + inviteuid);
    if (util.orgid == '15671'){
      return {
        title: '求职，企业招聘，人才培训……壹号人才欢迎您',
        path: '/pages/ghs_list/ghs_list?&inviteuid=' + inviteuid
        };
    } else if (util.orgid == '18535') {
      return {
        title: '家家走鬼市场，多多着数等你来',
        path: '/pages/ghs_list/ghs_list?&inviteuid=' + inviteuid
      };
    }else{
      return {
        title: that.data.org_name,
        path: '/pages/ghs_list/ghs_list?&inviteuid=' + inviteuid
      };
      // 家家公寓便利店24小时营业，欢迎选购
    }
  },


  showEWM: function (e) {
    var shareImgUrl = e.currentTarget.dataset.imgsrc;
    console.log("图片链接：" + shareImgUrl);
    wx.previewImage({
      current: shareImgUrl,
      urls: [shareImgUrl]
    })
  },

  goAtherPage: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.navigateTo({ url: url })
  },
  goAtherPageRedirect: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.redirectTo({ url: url })
  },

  //保存formId
  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);

    var path = e.detail.value.nav_path;
    if (path) {
      wx.redirectTo({ url: path })
    }
  },
  makeCallPhone: function (e) {
    var phoneNum = e.currentTarget.dataset.number;
    console.log("phoneNum:" + phoneNum);
    wx.makePhoneCall({
      phoneNumber: phoneNum,
      success: function (e) {
        console.log("make call success:", JSON.stringify(e));
      },
      fail: function (e) {
        console.log("make call fail:", JSON.stringify(e));
      }
    })
  },
  goMapView: function (e) {
    var addr = e.currentTarget.dataset.addr;
    var lat = parseFloat(addr.lat);
    var lon = parseFloat(addr.lon);
    wx.openLocation({
      latitude: lat,
      longitude: lon,
      scale: 20,
      name: addr.name,
      address: addr.address
    })
  },

  resetNavColor: function () {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },
})